package bramar.all;

import java.sql.*;
import java.io.*;
import java.util.*;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.DatabaseMetaData;
import java.sql.Statement;
 

 
 


public class MySqlToOracleTable   

{
     
	public MySqlToOracleTable(String table_name)throws SQLException, ClassNotFoundException 
	{
		Class.forName("org.gjt.mm.mysql.Driver");
		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection mcon=DriverManager.getConnection("jdbc:mysql:///mydb1","root","root");
		Connection ocon=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tiger");
		Statement st=mcon.createStatement();	
		Statement st1=ocon.createStatement();
			
		StringBuffer result = new StringBuffer();
		 
		try
		{
			StringBuffer sql=new StringBuffer();
			sql.append("select * from ");
			sql.append(table_name);
			ResultSet rs=st.executeQuery(sql.toString());
			ResultSetMetaData rsmd=rs.getMetaData();
			result.append("create table ");
			result.append(table_name);
			result.append("(");
			for(int i=1;i<=rsmd.getColumnCount();++i)
			{
				if(i!=1)
					result.append(',');
				result.append(rsmd.getColumnName(i));
				result.append(' ');
				String type=processType(rsmd.getColumnTypeName(i));
				result.append(type);

				if (rsmd.getPrecision(i) < 65535)
					{
						result.append('(');
						result.append(rsmd.getPrecision(i));
						if (rsmd.getScale(i) > 0)
						 {
							result.append(',');
							result.append(rsmd.getScale(i));
						 }
						result.append(") ");
					} else
					result.append(' ');
				
				if (rsmd.isNullable(i) == ResultSetMetaData.columnNoNulls)
					result.append("NOT NULL ");
				else
					result.append("NULL ");
				if (rsmd.isAutoIncrement(i))
					result.append(" auto_increment");
			}

      DatabaseMetaData dbmd = mcon.getMetaData();
      ResultSet primary = dbmd.getPrimaryKeys(null, null, table_name);
      boolean first = true;
      while (primary.next())
      {
        if (first)
        {
          first = false;
          result.append(',');
          result.append("PRIMARY KEY(");
        } else
          result.append(",");
 
        result.append(primary.getString("COLUMN_NAME"));
      }

      if (!first)
        result.append(')');

      result.append(" )");
st1.executeUpdate(result.toString());
 
    } catch (SQLException e)
    {
      e.printStackTrace();
    }
        }
        

  


   private static String processType(String columnTypeName)
    {
      
    
    if( columnTypeName.equalsIgnoreCase("varchar"))
      columnTypeName = "VARCHAR2";
    
 if( columnTypeName.equalsIgnoreCase("int"))
 columnTypeName = "NUMBER";

    return columnTypeName.trim();
    }
}


